package com.nervenets.web.controller;

import com.nervenets.web.i18n.Translator;
import com.nervenets.web.redis.GlobalService;
import com.nervenets.web.redis.GlobalVariablesService;
import org.springframework.web.servlet.ModelAndView;
import org.weixin4j.http.OAuthToken;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author joe
 *         Created at 14-7-3 上午10:01
 */
public abstract class BaseController {
    @Resource
    protected GlobalService globalService;
    @Resource
    protected GlobalVariablesService globalVariablesService;

    protected ModelAndView message(String resource) {
        return new ModelAndView("result", "message", Translator.translate(resource));
    }

    protected String propertiesMessage(String resource) {
        return Translator.translate(resource);
    }

    protected boolean loadProperties(Properties props, InputStream is) {
        try {
            if (is != null) {
                props.load(is);
                return true;
            }
        } catch (IOException ignore) {
            //异常忽略
            ignore.printStackTrace();
        }
        return false;
    }

    protected boolean loadProperties(Properties props, String path) {
        try {
            File file = new File(path);
            if (file.exists() && file.isFile()) {
                props.load(new FileInputStream(file));
                return true;
            }
        } catch (IOException ignore) {
            //异常忽略
            ignore.printStackTrace();
        }
        return false;
    }

    protected void weixinLogin() throws Exception {
        OAuthToken weChatAuthToken = globalVariablesService.getWeChatAuthToken();
        Global.getWeixin().setOauthToken(weChatAuthToken);
    }
}
